package com.dayu.finecomm.protocol.pojo;

import java.util.List;

/**
 * IOT数据域
 * 
 * @author XuJialiang
 * @since 2017-10-18 14:22:12
 * @version V1.0.0
 */
public class IotTSensor {
	public static enum DType {

		NOR(0), ARR(1);

		int val;

		private DType(int type) {
			this.val = type;
		}

		public int value() {
			return val;
		}

		@Override
		public String toString() {
			return Integer.toString(val);
		}
	}

	/**
	 * 数据类型
	 */
	private DType type;

	/**
	 * 通道号
	 */
	private String channel;

	/**
	 * 单个值
	 */
	private Object val;

	/**
	 * 数组值
	 */
	private List<Object> vals;

	/**
	 * 数据时间戳或者起始时间戳，单位：毫秒
	 */
	private Long timestamp;

	/**
	 * 间隔时间，单位：毫秒
	 */
	private Long interval;

	public IotTSensor(DType type, String channel, Object val) {
		this(type, channel, val, null, null);
	}

	public IotTSensor(DType type, String channel, Object val, Long time) {
		this(type, channel, val, null, time);
	}

	@SuppressWarnings("unchecked")
	public IotTSensor(DType type, String channel, Object val, Long timestamp,
			Long interval) {
		this.type = type;
		this.channel = channel;

		if (type.name().equals(DType.NOR.name())) {
			this.val = val;
			this.timestamp = interval;
		} else {
			this.vals = (List<Object>) val;
			this.timestamp = timestamp;
			this.interval = interval;
		}
	}

	/**
	 * 数据域字符串化
	 */
	public String toString() {
		StringBuilder sb = new StringBuilder();

		sb.append(channel);
		sb.append("=");

		if (type.name().equals(DType.NOR.name())) {
			if (val instanceof Double || val instanceof Float) {
				sb.append(String.format("%.6f", val));
			} else {
				sb.append(val);
			}

			if (null != timestamp) {
				sb.append(" ");
				sb.append(timestamp);
			}
		} else {
			for (int i = 0; i < vals.size(); i++) {
				Object val = vals.get(i);

				if (0 != i) {
					sb.append("|");
				}

				if (null != val) {
					if (val instanceof Double || val instanceof Float) {
						sb.append(String.format("%.6f", val));
					} else {
						sb.append(val);
					}
				}
			}

			if (null != interval) {
				sb.append(" ");
				sb.append(interval);

				if (null != timestamp) {
					sb.append("|");
					sb.append(timestamp);
				}
			}
		}

		return sb.toString();
	}
}
